import {defineStore, storeToRefs} from "pinia";

import {wsUrl, loginPrefixUrl, loginPrefixParams} from '~/settings'
import {useUserStore} from "@/store";
import router from "@/router";


export const useWebSocketStore = defineStore('websocket', {
    persist: true, //使用持久化插件
    state: () => {   //是一个函数，返回一个对象，用于存储状态
        return {
            isConnected: false,
            socket: null as WebSocket | null,
            messages: [],
            reconnectInterval: 1000 * 59, // 59秒重连一次
            reconnectTimer: null,
            heartbeatInterval: 1000 * 15, // 10秒发送一次心跳
            heartbeatTimer: null,
            loginUrl: '',
        }
    },
    getters: {},  //用于存储计算属性
    actions: {  //用于封装业务逻辑
        connect(url: string) {
            this.socket = new WebSocket(url);
            this.socket.addEventListener('open', () => {
                this.isConnected = true;
                console.log('WebSocket connected');
                this.resetHeartbeatTimer(); // 连接成功后重置心跳检测计时器
                this.resetReconnectTimer(); // 连接成功后重置重连计时器
                this.sendAuthentication(); // 连接成功后进行身份验证
            });

            this.socket.addEventListener('message', (event) => {
                const message = event.data;
                this.addMessage(message);
                console.log('Received message:', message);
                const response = JSON.parse(message)
                this.handleHeartbeatResponse(response); // 处理接收到的心跳响应
                this.handleLoginResponse(response); // 处理接收到的请求登录响应
                this.handleLoginSuccessResponse(response); // 处理接收到的登录成功响应
            });
            this.socket.addEventListener('close', () => {
                this.isConnected = false;
                console.log('WebSocket disconnected');
                this.stopHeartbeat(); // 连接断开时停止心跳检测
                this.stopReconnectTimer(); // 连接断开时停止重连计时器
            });

            this.socket.addEventListener('error', (error) => {
                console.error('WebSocket error:', error);
            });
        },
        send(message: string) {
            if (this.socket !== null && this.socket.readyState === WebSocket.OPEN) {
                this.socket.send(message);
            } else {
                console.error('WebSocket is not open');
            }
        },
        close() {
            this.stopReconnectTimer(); // 关闭连接时停止重连计时器
            this.stopHeartbeat(); // 关闭连接时停止心跳检测
            this.socket !== null && this.socket.close();
            this.socket = null
        },
        reconnect() {
            this.close()
            this.connect(wsUrl)
        },
        addMessage(message: any) {
            //@ts-ignore
            this.messages.push(message);
        },
        startReconnectTimer() {
            if (!this.reconnectTimer) {
                //@ts-ignore
                this.reconnectTimer = setInterval(() => {
                    console.log('Reconnecting...');
                    this.reconnect(); // 重连
                }, this.reconnectInterval);
            }
        },
        stopReconnectTimer() {
            //@ts-ignore
            clearInterval(this.reconnectTimer);
            this.reconnectTimer = null;
        },
        resetReconnectTimer() {
            this.stopReconnectTimer();
            this.startReconnectTimer();
        },
        resetHeartbeatTimer() {
            this.stopHeartbeat();
            this.startHeartbeat();
        },
        startHeartbeat() {
            if (!this.heartbeatTimer) {
                //@ts-ignore
                this.heartbeatTimer = setInterval(() => {
                    console.log('Sending heartbeat...');
                    this.sendHeartbeat(); // 发送心跳消息
                }, this.heartbeatInterval);
            }
        },
        stopHeartbeat() {
            //@ts-ignore
            clearInterval(this.heartbeatTimer);
            this.heartbeatTimer = null;
        },
        sendHeartbeat() {
            this.send(JSON.stringify({
                type: 'heartbeat',
                data: 'ping'
            } as IWSReq))
        },
        sendAuthentication() {
            const {token} = storeToRefs(useUserStore())
            this.send(JSON.stringify({
                type: 'authorization',
                data: token.value,
            } as IWSReq))
        },

        loginReq() {
            this.send(JSON.stringify({
                type: 'login'
            } as IWSReq))
        },


        handleHeartbeatResponse(response: any) {
            if (response.code === 0 && response.msg === 'WS心跳检测') {
            }
        },
        handleLoginResponse(response: any) {
            if (response.code === 0 && response.msg === 'WS请求登录') {
                const q = loginPrefixParams + response.data
                this.loginUrl = loginPrefixUrl + q
            }
        },
        handleLoginSuccessResponse(response: any) {
            if (response.code === 0 && response.msg === 'WS登录成功') {
                const userStore = useUserStore()
                userStore.loginSuccess(response.data.userInfo, response.data.token, response.data.refreshToken)
                router.push('/home')
                window.$message.success('登录成功')
            }
        },
    },
})